<template lang="pug">
.waterquality-wrap
  ECharts.line-chart(
    ref="echarts"
    :options="options"
    auto-resize)
  ECharts.pie-chart(
    ref="pie"
    :options="pieOptions"
    auto-resize)
</template>

<script>
/**
 * @name WaterQuality 基础折线图
 * @author wangrf
 * @description 展示类目折线图
 */
import {keyBy, countBy} from 'lodash'
import DefaultChart from './DefaultChart'
export default {
  name: 'WaterQuality',
  props: {
    target: String,
    parameterList: Array,
    devicesData: Array
  },
  components: {
    DefaultChart
  },
  data () {
    // console.log(this.target, this.parameterList, this.devicesData)
    return {
      pieOptions: {},
      options: {}
    }
  },
  computed: {
    isMulti () {
      return this.devicesData.length > 1
    },
    currentTarget () {
      console.log('computed', this.target)
      return keyBy([...this.parameterList], 'mark')[this.target]
    },
    // default需要的计算值
    yAxisName () {
      const label = this.currentTarget.label ? this.currentTarget.label : ''
      const unit = this.currentTarget.unit ? `(${this.currentTarget.unit})` : ''
      return label ? `${label}${unit}` : ''
    },
    xAxis () {
      const data = this.devicesData[0].data.map(({recordTime}) => this.$moment(recordTime, 'x').format('YYYY-MM-DD HH:mm'))
      return [{
        type: 'category',
        boundaryGap: false,
        axisLine: {onZero: true},
        data: data
      }]
    },
    series () {
      return this.devicesData.reduce((result, device) => {
        return [
          ...result,
          {
            type: 'line',
            symbolSize: 8,
            showSymbol: false,
            hoverAnimation: false,
            name: this.isMulti ? (device.siteName || '-') + '(' + device.siteCode + ')' : this.currentTarget.label,
            data: device.data.map((data) => data[this.currentTarget.mark] || data[this.currentTarget.mark] === 0 ? this.formatValue(data[this.currentTarget.mark]) : null),
            markPoint: {
              symbol: 'pin',
              symbolSize: (value, params) => {
                let width = this.formatValue(value).length * 14
                width = (width < 40) ? 40 : width
                return [width, 40]
              },
              label: {
                formatter: ({seriesName, name, value}) => {
                  return `${this.formatValue(value) || '-'}`
                }
              },
              data: [
                {type: 'max', name: '最大值'},
                {type: 'min', name: '最小值'}
              ]
            }
            // markPoint: {
            //   symbolSize: 1,
            //   symbolOffset: [0, '50%'],
            //   label: {
            //     offset: [0, -15],
            //     formatter: ({seriesName, name, value}) => {
            //       return `${seriesName}${name}：${this.formatValue(value)} ${this.currentTarget.unit ? this.currentTarget.unit : ''}`
            //     },
            //     backgroundColor: 'rgba(0,0,0,0.7)',
            //     borderRadius: 15,
            //     padding: [4, 10],
            //     lineHeight: 15,
            //     height: 15,
            //     distance: 20,
            //     color: '#fff',
            //     textBorderColor: '#000',
            //     fontSize: 12,
            //     fontWeight: 'bold',
            //     fontFamily: 'Microsoft YaHei',
            //     textBorderWidth: 1
            //   },
            //   data: this.isMulti ? [] : [
            //     {type: 'max', name: '最大值'},
            //     {type: 'min', name: '最小值'}
            //   ]
            // }
          }
        ]
      }, [])
    },
    legend () {
      const data = this.isMulti ? this.devicesData.reduce((result, device) => {
        return [ ...result, (device.siteName || '-') + '(' + device.siteCode + ')' ]
      }, []) : [this.currentTarget.label]
      return data
    },
    tipPosition () {
      return this.isMulti ? {
        position (pos, params, el, elRect, size) {
          var obj = {top: 10}
          obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 30
          return obj
        }
      } : {}
    }
  },
  watch: {
    devicesData () {
      this.renderChart()
    },
    target () {
      this.renderChart()
    }
  },
  methods: {
    getQualityRate () {
      // console.log('数据', [...this.devicesData[0].data])
      const qual = countBy([...this.devicesData[0].data], (item) => {
        const target = this.currentTarget
        if (!(item[target.mark] || item[target.mark] === 0)) {
          return 'unCautch'
        } else if (item[target.mark] <= target.maxValue && item[target.mark] >= target.minValue) {
          return 'qual'
        }
        return 'unqual'
      })
      return qual
    },
    renderChart () {
      this.options = {
        color: ['#0000EE', '#CD0000', '#fec450', '#fc5929', '#83c9c7', '#2e4672', '#a1bb1c', '#fdad5b'],
        xAxis: this.xAxis,
        yAxis: [{
          name: this.yAxisName,
          type: 'value',
          scale: true
        }],
        series: this.series,
        axisPointer: {
          link: {xAxisIndex: 'all'}
        },
        grid: {
          show: true,
          left: 50,
          right: 12,
          top: '8%',
          bottom: '24%'
        },
        dataZoom: [
          {
            show: true,
            realtime: true,
            y: '85%',
            start: 0,
            end: 100
          },
          {
            type: 'inside',
            realtime: true,
            start: 0,
            end: 100
          }
        ],
        legend: {
          type: 'scroll',
          width: '92%',
          x: 'center',
          y: '94%',
          data: this.legend
        },
        tooltip: {
          ...this.tipPosition,
          trigger: 'axis',
          axisPointer: {
            snap: true,
            label: {
              show: false
            },
            type: 'cross'
          },
          textStyle: {
            fontSize: 12,
            fontWeight: 'bold',
            fontFamily: 'Microsoft YaHei'
          },
          formatter: (param) => {
            const text = param.reduce((result, site) => {
              return result + `<div>${site.marker}${site.seriesName}：${this.formatValue(site.value) || '-'} ${this.currentTarget.unit || ''}</div>`
            }, param[0].axisValue)
            return text
          }
        }
      }
      this.pieOptions = {
        title: {
          text: this.currentTarget.label + '合格率',
          subtext: '',
          y: 48,
          x: 'center'
        },
        color: ['#91c7ae', '#2f4554', '#61a0a8'],
        tooltip: {
          trigger: 'item',
          formatter: '{b}  ({d}%) <br/>{a}  {c}',
          textStyle: {
            fontSize: 12,
            fontWeight: 'bold',
            fontFamily: 'Microsoft YaHei'
          }
        },
        legend: {
          // type: 'scroll',
          x: 'center',
          bottom: 10,
          radius: '42%',
          itemWidth: 14,
          itemGap: 6,
          data: ['合格', '不合格', '未记录']
        },
        grid: [{
          x: '8%',
          y: '20%',
          width: '38%',
          height: '60%'}],
        series: [
          {
            name: '数量',
            type: 'pie',
            center: ['50%', '50%'],
            avoidLabelOverlap: false,
            label: {
              normal: {
                show: false
              },
              emphasis: {
                show: false
              }
            },
            labelLine: {
              normal: {
                show: false
              }
            },
            itemStyle: {
              borderColor: '#ececec',
              borderWidth: '1',
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            data:
              [
                {value: this.getQualityRate().qual, name: '合格'},
                {value: this.getQualityRate().unqual, name: '不合格'},
                {value: this.getQualityRate().unCautch, name: '未记录'}
              ]
          }
        ]
      }
    },
    formatValue (value) {
      return (value != null && value !== undefined) ? parseFloat(value).toFixed(3) : null
    }
  }
}
</script>

<style lang="sass" scoped>
.waterquality-wrap
  width: 100%
  height: 100%
  display: flex
  align-items: stretch
  .line-chart
    flex: 3
    height: 100%  !important
  .pie-chart
    flex: 1
    height: 100%
</style>
